package com.df.hitime.common;

import org.springframework.util.StringUtils;

import java.lang.reflect.Field;
import java.util.*;

/**
 * @author liurx
 * @date 2018/11/20 11:01
 */
public class Utils {

    /**
     * 解析对象中的字典，以key-value形式封装成Map
     * @param object
     * @return
     */
    public static HashMap ObjectFiledToMap(Object object){

        Class orderClass = (Class) object.getClass();
        /*
         * 得到类中的所有属性集合
         */
        Field[] field = orderClass.getDeclaredFields();
        HashMap<String, String> paramMap = new HashMap<>();
        for (int i = 0; i < field.length; i++) {
            Field f = field[i];
            f.setAccessible(true); // 设置些属性是可以访问的
            String key = f.getName();// key:得到属性名
            Object value = null;// 得到此属性的值
            try {
                value = f.get(object);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            if (value != null && !StringUtils.isEmpty(value))
                paramMap.put(key, value.toString());
        }
        return paramMap;
    }


    /**
     * 将Map中字段按字典升序排序 非空字段拼接成url参数格式
     * @param paraMap
     * @return
     */
    public static String formatUrlMap(Map<String, String> paraMap) {
        String buff = "";
        Map<String, String> tmpMap = paraMap;
        try {
            List<Map.Entry<String, String>> infoIds = new ArrayList<Map.Entry<String, String>>(tmpMap.entrySet());
            // 对所有传入参数按照字段名的 ASCII 码从小到大排序（字典序）
            Collections.sort(infoIds, new Comparator<Map.Entry<String, String>>() {

                @Override
                public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2) {
                    return (o1.getKey()).toString().compareTo(o2.getKey());
                }
            });
            // 构造URL 键值对的格式
            StringBuilder buf = new StringBuilder();
            for (Map.Entry<String, String> item : infoIds) {
                if (!StringUtils.isEmpty(item.getKey())) {
                    String key = item.getKey();
                    String val = item.getValue();
                    buf.append(key + "=" + val);
                    buf.append("&");
                }

            }
            buff = buf.toString();
            if (buff.isEmpty() == false) {
                buff = buff.substring(0, buff.length() - 1);
            }
        } catch (Exception e) {
            return null;
        }
        return buff;
    }

}
